﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Net;
using System.Runtime.Remoting.Proxies;
using System.Threading;
using System.Windows.Forms;
using Conusic;
using Conusic.Properties;

namespace ConusicUI
{
    /// <summary>
    /// Description of ProxyConfiguration.
    /// </summary>
    public partial class ProxyConfiguration : UserControl
    {
        private Config.ProxyType proxyTypeSelected
        {
            get
            {
                if (radioButtonAutoProxy.Checked) return Config.ProxyType.Automatic;
                else if (radioButtonDirect.Checked) return Config.ProxyType.Direct;
                else if (radioButtonManual.Checked) return Config.ProxyType.Manual;
                else throw new ArgumentException("no one radio button selected");
            }
        }

        private bool connectionSuccessfullyChecked = false; 
        public bool ConnectionSuccessfullyChecked
        {
            get { return connectionSuccessfullyChecked; }
            private set { connectionSuccessfullyChecked = value; }
        }

        public ProxyConfiguration()
        {
            ConnectionSuccessfullyChecked = false;
            InitializeComponent();
            var proxyType = (Config.ProxyType)Settings.Default.ProxyType;
            switch (proxyType)
            {
                case Config.ProxyType.Automatic:
                    radioButtonAutoProxy.Select();
                    break;
                case Config.ProxyType.Direct:
                    radioButtonDirect.Select();
                    break;
                case Config.ProxyType.Manual:
                    radioButtonManual.Select();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            SetEnablePasswordProxy(checkBoxAuthRequire.Checked);
            checkBoxAuthRequire.Checked = Settings.Default.ProxyAuth ;
            textBoxAddress.Text = Settings.Default.ProxyAddress;
            textBoxPort.Text = Settings.Default.ProxyPort.ToString();
            textBoxUsername.Text = Settings.Default.ProxyUser;
            textBoxPassword.Text = Settings.Default.ProxyPass;
        }

        private void SetEnableManualConfiguration(bool withoutProxyAuthEnabled)
        {
            textBoxAddress.Enabled = withoutProxyAuthEnabled;
            labelDelemiter.Enabled = withoutProxyAuthEnabled;
            labelAddress.Enabled = withoutProxyAuthEnabled;
            textBoxPort.Enabled = withoutProxyAuthEnabled;
            labelPort.Enabled = withoutProxyAuthEnabled;
        }

        private void SetEnablePasswordProxy(bool w)
        {
            this.textBoxPassword.Enabled = w;
            this.textBoxUsername.Enabled = w;
            labelPassword.Enabled = w;
            labelLogin.Enabled = w;
        }

        private void RadioButtonCheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonAutoProxy.Checked)
            {
                SetEnableManualConfiguration(false);
            }
            else if (radioButtonDirect.Checked)
            {
                SetEnableManualConfiguration(false);
            }
            else if (radioButtonManual.Checked)
            {
                SetEnableManualConfiguration(true);
            }
        }

        private void CheckBoxAuthRequireCheckedChanged(object sender, EventArgs e)
        {
            SetEnablePasswordProxy(checkBoxAuthRequire.Checked);
        }

        private void Button1Click(object sender, EventArgs e)
        {
            if (!ValidateForm())
            {
                return;
            }

            SetProxySettings();

            this.UseWaitCursor = true;

            try
            {
                string page = SimpleHttp.RequestVkontaktePage("help.php?page=about");
                // Durov never remove himself :-)
                if (page.Contains(@"href=""/id1"""))
                {
                    textBoxResult.Text =
                        @"Все хорошо. Если в будущем будет появляться это окно, обратитесь к разработчику";
                    textBoxResult.BackColor = Color.LightGreen;
                    this.ConnectionSuccessfullyChecked = true;
                }
                else
                {
                    this.connectionSuccessfullyChecked = false;
                    throw new WebException("Страница получена, но ответ неверен. " +
                        "Возможно, закрыт доступ к Vkontakte.ru или используется неверный прокси сервер");
                }
            }
            catch (Exception exception)
            {
                textBoxResult.Text =
                    String.Format("Запрос неудачен. Произошла ошибка  {0}. " +
                    "Перепроверьте настройки прокси, в случае необходимости," +
                    " обратитесь к вашему системному администратору {1}",
                    exception.Message,
                    DateTime.Now);
                textBoxResult.BackColor = Color.LightPink;
            }finally
            {
                this.UseWaitCursor = false;
            }
        }

        private void SetProxySettings()
        {
            int port = int.Parse(textBoxPort.Text);
            Config.Instance.UpdateProxyParams(
                proxyTypeSelected,
                checkBoxAuthRequire.Checked,
                textBoxAddress.Text,
                port,
                textBoxUsername.Text,
                textBoxPassword.Text);
        }

        private bool ValidateForm()
        {
            errorProvider1.Clear();

            int x;
            bool validation = true;
            if (!int.TryParse(textBoxPort.Text, out x) || x > 65536 || x < 0)
            {
                errorProvider1.SetError(textBoxPort, @"Порт должен быть целым числом от 1 до 65536");
                validation = false;
            }
            if (radioButtonManual.Checked && String.IsNullOrEmpty(textBoxAddress.Text))
            {
                errorProvider1.SetError(textBoxAddress, @"Введите адрес прокси");
                validation = false;
            }

            if (checkBoxAuthRequire.Checked)
            {
                if (String.IsNullOrEmpty(textBoxUsername.Text))
                {
                    errorProvider1.SetError(textBoxUsername, @"введите пользователя прокси");
                    validation = false;
                }
                if (String.IsNullOrEmpty(textBoxPassword.Text))
                {
                    errorProvider1.SetError(textBoxPassword, @"введите пароль прокси");
                    validation = false;
                }
            }
            return validation;
        }

        public bool SaveSettings()
        {
            if (!Validate())
            {
                return false;
            }
            SetProxySettings();

            Settings.Default.ProxyType =  (int)proxyTypeSelected;
            Settings.Default.ProxyAuth =  checkBoxAuthRequire.Checked ;
            Settings.Default.ProxyUser =  textBoxUsername.Text;
            Settings.Default.ProxyPass =  textBoxPassword.Text;
            Settings.Default.ProxyAddress =  textBoxAddress.Text;
            Settings.Default.ProxyPort =  int.Parse(textBoxPort.Text);
            return true;
        }

    }
}